package util

import (
	"encoding/binary"
	"fmt"
	"net"
	"strconv"
	"strings"
)

func ByteToString(info string) string {

	var infoid string
	var data []byte = []byte(info)
	for _, byte := range data {
		infoid += fmt.Sprintf("%02x", byte)
	}
	return infoid
}

func Inet_ntoa(ipnr int) net.IP {
	var bytes [4]byte
	bytes[0] = byte(ipnr & 0xFF)
	bytes[1] = byte((ipnr >> 8) & 0xFF)
	bytes[2] = byte((ipnr >> 16) & 0xFF)
	bytes[3] = byte((ipnr >> 24) & 0xFF)
	return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0]).To4()
}

func Inet_aton(ipnr net.IP) int {
	bits := strings.Split(ipnr.String(), ".")

	b0, _ := strconv.Atoi(bits[0])
	b1, _ := strconv.Atoi(bits[1])
	b2, _ := strconv.Atoi(bits[2])
	b3, _ := strconv.Atoi(bits[3])

	var sum int
	sum += int(b0) << 24
	sum += int(b1) << 16
	sum += int(b2) << 8
	sum += int(b3)

	return sum
}

func Int2Byte(data uint16) (ret []byte) {
	bytes := make([]byte, 2)
	binary.BigEndian.PutUint16(bytes, data)
	return bytes
}

func iptobyte(addr string) []byte {
	return net.ParseIP(addr).To4()
}
func porttobyte(port string) []byte {

	data, _ := strconv.ParseUint(port, 10, 16)
	return Int2Byte(uint16(data))
}

func AddrtoByte(addr string, addrport string) (ret []byte, err error) {
	bytes := make([]byte, 6)
	ip := iptobyte(addr)
	port := porttobyte(addrport)
	bytes = append(ip, port...)
	return bytes, nil
}

func BtPrint(addr string) {

	var b []byte = []byte(addr)
	IP := make(net.IP, len(b)-2)
	copy(IP, b[:len(b)-2])
	//// LittleEndian
	//// BigEndian
	Port := int(binary.BigEndian.Uint16(b[len(b)-2:]))
	fmt.Println(IP)
	fmt.Println(Port)

}
